package com.crm.service.system.impl;

import com.crm.context.BaseContext;
import com.crm.dto.MenuDto;
import com.crm.mapper.system.MenuMapper;
import com.crm.pojo.Menu;
import com.crm.service.system.MenuService;
import com.crm.vo.TreeselectVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 查询菜单列表
     *
     * @return
     */
    @Override
    public List<Menu> queryMenuList() {
        return menuMapper.queryMenuList();
    }

    /**
     * 删除菜单
     *
     * @param menuId
     */
    @Override
    public void deleteMenu(Long menuId) {
        menuMapper.deleteMenu(menuId);
    }

    /**
     * 新增参数
     *
     * @param dto
     */
    @Override
    public void addMenu(MenuDto dto) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(dto, menu);
        //补齐数据
        menu.setCreateBy(String.valueOf(BaseContext.getCurrentId()));
        menuMapper.addMenu(menu);

    }

    /**
     * 根据id查询菜单
     *
     * @param menuId
     * @return
     */
    @Override
    public Menu queryById(Long menuId) {
        return menuMapper.queryById(menuId);
    }

    /**
     * 修改菜单
     *
     * @param menu
     */
    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateMenu(menu);
    }


    @Override
    public List<TreeselectVO> getTree() {
        List<TreeselectVO> menuList = menuMapper.selectAllMenus();
        List<TreeselectVO> list = treeSelectVOList(menuList);
        return list;
    }

    private List<TreeselectVO> treeSelectVOList(List<TreeselectVO> menuList) {
        List<TreeselectVO> result = new ArrayList<>();
        menuList.forEach(d -> {
            if (d != null && d.getParentId() == 0) {
                result.add(findChildren(d, menuList));
            }
        });
        return result;
    }

    private TreeselectVO findChildren(TreeselectVO parent, List<TreeselectVO> menuList) {
        List<TreeselectVO> children = new ArrayList<>();
        menuList.forEach(d -> {
            if (d != null && parent.getId().equals(d.getParentId())) {
                children.add(findChildren(d, menuList));
            }
        });
        parent.setChildren(children);
        return parent;
    }





}
